package com.fs.uc.api.user.service;

import com.fs.uc.api.user.dto.RespUser;
import com.fs.uc.core.behavior.PersonBehavior;
import com.fs.uc.core.permcheck.PermissionCheckerFactory;
import com.fs.uc.core.SubjectType;
import com.fs.uc.base.domain.*;
import com.fs.uc.base.repo.AdditionalRoleRepository;
import com.fs.uc.base.repo.OrgRepository;
import com.fs.uc.base.repo.PersonRepository;
import com.fs.uc.base.repo.RoleRepository;
import com.fs.uc.core.relationship.RelationFetcherFactory;
import com.fs.uc.security.JwtUtil;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Set;

/**
 * @author 崔超
 * 2021/12/7
 */
@ApplicationScoped
public class CommonService {
    @Inject
    PersonRepository personRepo;
    @Inject
    OrgRepository orgRepo;
    @Inject
    PermissionCheckerFactory permissionCheckerFactory;
    @Inject
    PersonBehavior personBehavior;
    @Inject
    JwtUtil jwtUtil;
    @Inject
    RelationFetcherFactory rfFactory;


    public RespUser getSubjectInfo(Long subjectId, SubjectType subjectType) {
        if (subjectType == SubjectType.Org) {
            Org org = orgRepo.getById(subjectId);
            return new RespUser(org.name, org.id);
        } else if (subjectType == SubjectType.Person) {
            Person person = personRepo.getById(subjectId);
            return new RespUser(person.name, person.id);
        }
        throw new RuntimeException("SubjectType内容非法");
    }

    public Set<FunctionalModule> getAuthorizedModule(Long subjectId, SubjectType subjectType) {
        return permissionCheckerFactory.getChecker(subjectType).getAuthorizedModule(subjectId);
    }

    public Set<Role> getRolesOfUser(Long subjectId, SubjectType subjectType) {
        return permissionCheckerFactory.getChecker(subjectType).getRoles(subjectId);
    }

    public String getIdentityType(Long subjectId, SubjectType subjectType) {
        if (subjectType == SubjectType.Org) {
            return PersonBehavior.PersonIdentity.ParkAdmin.name();
        }
        PersonBehavior.PersonIdentity identity = personBehavior.getIdentity(subjectId);
        return identity.name();
    }

    public String switchOrg(Long personId, Long orgId) {
        Person person = personBehavior.switchCurrentOrg(personId, orgId);
        return jwtUtil.buildToken(person);
    }

    public Long fetchUserParkId(SubjectType type, Long personId) {
        if (type != SubjectType.Person) {
            throw new RuntimeException("令牌主体类型非个人");
        }
        return rfFactory.fetcher(SubjectType.Person).inWhichPark(personId);
    }
}
